package com.mxpio.erp.mes.aspect;

import com.mxpio.erp.common.mes.entity.MesScanLog;
import com.mxpio.erp.common.mes.vo.ScanInfoVo;
import com.mxpio.erp.common.technology.entity.WorkUnit;
import com.mxpio.erp.mes.event.ScanAfterSaveLogEvent;
import com.mxpioframework.common.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import java.util.Date;

@Aspect
@Component
@Slf4j
public class ScanLogAspect {
    @Autowired
    private ApplicationEventPublisher eventPublisher;

    @Pointcut("execution(* com.mxpio.erp.mes.controller.*.scan*(..))")
    public void excudeService() {
    }

    @Around("excudeService()")
    public Object doAround(ProceedingJoinPoint pjp){
        Object result = null;
        try {
            result = pjp.proceed();
        } catch (Throwable e) {
            log.error(e.getMessage());
        }
        if(result instanceof Result){
            Result res = (Result)result;
            Object[] args = pjp.getArgs();
            ScanInfoVo scanInfoVO = (ScanInfoVo)args[0];
            MesScanLog mesSmScanLog = new MesScanLog();
            mesSmScanLog.setBizNo(scanInfoVO.getBizNo());
            mesSmScanLog.setBatchCode(scanInfoVO.getBatchCode());
            mesSmScanLog.setTaskCode(scanInfoVO.getTaskCode());
            mesSmScanLog.setOperator(scanInfoVO.getOperator());
            WorkUnit workUnit = scanInfoVO.getWorkUnit();
            if (workUnit!=null){
                mesSmScanLog.setWorkUnitCode(workUnit.getWorkUnitCode());
                mesSmScanLog.setWorkUnitName(workUnit.getWorkUnitName());
            }
            if(res.isSuccess()){
                Object data = res.getResult();
                if(data instanceof ScanInfoVo){
                    ScanInfoVo resInfo = (ScanInfoVo) data;
                    mesSmScanLog.setScanTime(resInfo.getScanTime());
                }
            }else{
                mesSmScanLog.setScanTime(new Date());
            }
            mesSmScanLog.setResStatus(res.isSuccess()?"0":"1");
            mesSmScanLog.setResMsg(res.getMessage());
            eventPublisher.publishEvent(new ScanAfterSaveLogEvent(mesSmScanLog));
        }
        return result;
    }
}
